package com.elite.groovy.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.elite.groovy.util.EliteBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;

import javax.sql.DataSource;

@Configuration
public class EliteBeanConfig {
    private static final Logger log = LoggerFactory.getLogger(EliteBeanConfig.class);
    @Value("${spring.datasource.jndiName:#{null}}")
    private String jndiName;

    public EliteBeanConfig() {
    }

    @Primary
    @Bean(
            value = {"master"},
            destroyMethod = ""
    )
    public DataSource master() {
        if (StringUtils.isNotEmpty(this.jndiName)) {
            log.info("使用共享数据源: {}", this.jndiName);
            JndiDataSourceLookup lookup = new JndiDataSourceLookup();
            lookup.setResourceRef(true);
            return lookup.getDataSource(this.jndiName);
        } else {
            return DruidDataSourceBuilder.create().build();
        }
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.master());
    }

    @Bean
    public EliteBean ebean() {
        EliteBean eliteBean = new EliteBean();
        eliteBean.setDataSource(this.master());
        eliteBean.setTransactionManager(this.transactionManager());
        return eliteBean;
    }
}
